<?php

namespace app\common\model;

use think\Env;
use think\Model;

/**
 * 模型
 */
class OrderGoods extends Model
{
    // 表名
    protected $name = 'order_goods';
    protected $deleteTime = false;
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 追加属性
    protected $append = [

    ];


    public function goods()
    {
        return $this->belongsTo(Goods::class, 'goods_id');
    }

    public function od()
    {
        return $this->belongsTo(Order::class, 'order_id');
    }

    public function getGoodsImageAttr($value)
    {
        return !empty($value) ? Env::get('app.app_host') . $value : '';
    }

    public function setGoodsImageAttr($value)
    {
        if (!empty($value)){
            $arr = parse_url($value);
            return $arr['path'];
        }
        return '';
    }

    /**
     * 获取店铺商品销量
     * @param $shop_id
     * @param $goods_id
     * @return int
     * @throws \think\Exception
     */
    public static function getSaleNumByShopGoodsId($shop_id, $goods_id): int
    {

//        return self::alias('og')->where(['og.shop_id' => $shop_id, 'og.goods_id' => $goods_id])->join('order o', ['o.id = og.order_id and o.order_status > 1 and o.order_status < 5'], 'LEFT')->count('og.id') ?? 0;
        return self::alias('og')
                ->join('order o', 'o.id = og.order_id', 'LEFT')
                ->where(['og.shop_id' => $shop_id, 'og.goods_id' => $goods_id,'o.order_status'=>['in',[2,3,4]]])->count('og.id') ?? 0;

    }

}
